<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import {
  JxtechPageTable,
  JxtechPageTableColumn,
  JxtechPageTableExpType,
  useJxtechPageTable,
  JxtechPageTableProps
} from "@whjxtech/jxtech-component";
import { commonList } from "@/api/modules/org/code-list";
import { messageSuccessTip, messageWarningTip } from "@/utils/message-config";
import { ElMessageBox } from "element-plus";
import { ServiceApi } from "@/api/modules/_base";
import { JxtechPageTableDeleteConfig } from "@/comp-ext";

const props = withDefaults(defineProps<JxtechPageTableProps>(), {
  data: () => [],
  showHeader: true,
  fullTable: false,
  headerRowClassName: "jxtech-table-header-row",
  toolbarItem: () => [
    {
      key: "selection",
      class: "selection",
      icon: "icon-selection",
      tooltip: "jxtech.table.selectedData"
    },
    {
      key: "filter",
      class: "filter",
      icon: "icon-filter",
      tooltip: "jxtech.table.columnSettings"
    },
    { key: "size", class: "size", icon: "icon-size", tooltip: "jxtech.table.tableSize" }
  ],
  showFooter: true,
  showToolbar: true,
  paginationPageSize: 25,
  paginationPageSizeArray: () => [10, 25, 50, 100],
  paginationLayout: "total, sizes, prev, pager, next",
  paginationMarginTop: 12,
  basicCardMarginTop: 20,
  mainLayoutPadding: 24,
  footerHeight: 0,
  tabsHeight: 0
});

//定义page-table的值
const PageTableRef = ref();
const {
  loadTable,
  reloadTable,
  expData,
  getSelectionData,
  getSelectionPkList,
  clearSelection,
  getElTableInstance,
  clearSort,
  clearFilter,
  fitTableHeight
} = useJxtechPageTable(PageTableRef);

const PageTableState = reactive({
  tableColumn: props.tableColumn,
  slotList: [] as string[],
  init() {
    PageTableState.handleTableColumn();
  },
  handleTableColumn() {
    if (props.tableColumn && props.tableColumn.length > 0) {
      props.tableColumn.forEach(column => {
        PageTableState.handleDictionary(column);
        PageTableState.handleSlot(column);
      });
    }
  },
  ////处理数据字典搜索
  handleDictionary(column: JxtechPageTableColumn) {
    if (column.filter && column.filter.type === "dictionary" && column.filter.codeItemId) {
      column.filter.textKey = "value";
      column.filter.valueKey = "key";
      column.filter.loadData = () => {
        if (column.filter && column.filter.codeItemId) {
          return commonList(column.filter.codeItemId);
        }
        return null;
      };
      column.filter.type = "function";
    }
  },
  //处理插槽
  handleSlot(column: JxtechPageTableColumn) {
    if (column.slot) PageTableState.slotList.push(column.slot);
  },
  /**删除选中的数据 */
  deleteSelectionDataList(servicelApi: ServiceApi, deleteConfig?: JxtechPageTableDeleteConfig) {
    const selectionData = getSelectionData();
    if (!selectionData || selectionData.length == 0) {
      messageWarningTip("没有选择需要删除的数据!");
      return;
    }
    ElMessageBox.confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      lockScroll: false
    }).then(() => {
      servicelApi.saveMulti({ insert: [], update: [], delete: selectionData }, deleteConfig?.deleteExtData).then(() => {
        messageSuccessTip("数据删除成功!");
        if (deleteConfig?.refreshTable !== false) {
          loadTable();
        }
      });
    });
  },
  /**删除选中的主键集合 */
  deleteSelectionPkList(servicelApi: ServiceApi, deleteConfig?: JxtechPageTableDeleteConfig) {
    const selectionPkList: string[] = getSelectionPkList();
    if (!selectionPkList || selectionPkList.length == 0) {
      messageWarningTip("没有选择需要删除的数据!");
      return;
    }
    ElMessageBox.confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      lockScroll: false
    }).then(() => {
      servicelApi.saveMultiDelete(selectionPkList, deleteConfig?.deleteExtData).then(() => {
        messageSuccessTip("数据删除成功!");
        if (deleteConfig?.refreshTable !== false) {
          PageTableRef.value.loadTable();
        }
      });
    });
  },
  /**根据主键删除对象 */
  deleteSelectionPk(servicelApi: ServiceApi, deleteConfig?: JxtechPageTableDeleteConfig) {
    const selectionPkList: string[] = getSelectionPkList();
    if (!selectionPkList || selectionPkList.length == 0) {
      messageWarningTip("没有选择需要删除的数据!");
      return;
    }
    ElMessageBox.confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      lockScroll: false
    }).then(() => {
      servicelApi.delete(selectionPkList.toString(), deleteConfig?.deleteExtData).then(() => {
        messageSuccessTip("数据删除成功!");
        if (deleteConfig?.refreshTable !== false) {
          PageTableRef.value.loadTable();
        }
      });
    });
  }
});

PageTableState.init();

defineExpose({
  /**
   * 加载表格
   */
  loadTable: () => loadTable(),
  /**
   * 重载表格
   */
  reloadTable: () => reloadTable(),
  /**
   * 导出文件
   */
  expData: (expType: JxtechPageTableExpType) => expData(expType),
  /**
   * 获取选择的数据
   */
  getSelectionData: () => getSelectionData(),
  /**
   * 获取选中的数据的主键集合
   */
  getSelectionPkList: () => getSelectionPkList(),
  /**
   * 清理选择的数据
   */
  clearSelection: () => clearSelection(),
  /**
   * 清理排序
   */
  clearSort: () => clearSort(),
  /**
   * 清理筛选
   * @param filters 需要清理列筛选的prop数组 不穿 则清理所有
   */
  clearFilter: (columnKeyArray?: string[]) => clearFilter(columnKeyArray),
  /**获取elementui table的ref对象 */
  getElTableInstance: () => getElTableInstance(),
  fitTableHeight: () => fitTableHeight(),
  deleteSelectionDataList: (servicelApi: ServiceApi, deleteConfig?: JxtechPageTableDeleteConfig) =>
    PageTableState.deleteSelectionDataList(servicelApi, deleteConfig),
  deleteSelectionPkList: (servicelApi: ServiceApi, deleteConfig?: JxtechPageTableDeleteConfig) =>
    PageTableState.deleteSelectionPkList(servicelApi, deleteConfig),
  deleteSelectionPk: (servicelApi: ServiceApi, deleteConfig?: JxtechPageTableDeleteConfig) =>
    PageTableState.deleteSelectionPk(servicelApi, deleteConfig)
});

watch(
  () => props.tableColumn,
  val => {
    PageTableState.tableColumn = [...val];
    PageTableState.init();
  },
  { deep: true }
);
</script>
<template>
  <JxtechPageTable
    v-bind="{ ...props }"
    ref="PageTableRef"
    :row-key="rowKey"
    :table-column="tableColumn"
    :load-data="loadData"
    border
  >
    <template v-for="item in PageTableState.slotList" #[item]="scope">
      <slot
        :name="item"
        :row="scope.row"
        :column="scope.column"
        :index="scope.index"
        :expanded="scope.expanded || '只有展开行有该属性'"
      >
        {{ item }}
      </slot>
    </template>
  </JxtechPageTable>
</template>
